package cn.b.sky.schedule.servlet;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.schedule.job.GlobalJobListenerManager;
import cn.b.sky.schedule.job.TimeJobUtils;
import cn.b.sky.schedule.model.TimedJobInfo;
import cn.b.sky.schedule.service.TimedJobService;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;
import java.util.TimeZone;

/**
 * 
 * 定时任务监听器
 * 
 * @author kesy
 * 
 */
@WebListener
public class TimedJobServletContextListener implements ServletContextListener {

  private static final Logger LOGGER = LoggerFactory.getLogger(TimedJobServletContextListener.class);

  @Override
  public void contextInitialized(ServletContextEvent sce) {
    try {
      // 得到Bean工厂
      BeanFactory bf = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
      // 得到任务调度器
      Scheduler scheduler = (Scheduler) bf.getBean("scheduler");
      // 得到定时任务服务类
      TimedJobService timedJobService = (TimedJobService) bf.getBean("timedJobService");
      // 所需要定时执行的任务集合启用
      List<TimedJobInfo> jobs = timedJobService.selectEnableTimedJob(SystemConstant.COMMON_STATUS_ON);
      //添加全局监听器
      scheduler.getListenerManager().addJobListener(new GlobalJobListenerManager());
      if (null != jobs) {
        for (TimedJobInfo job : jobs) {
          // 新建JobDetail
          JobDetail jobDetail = TimeJobUtils.getJobDetail(job);
          
          // 新建定时器
          CronTriggerFactoryBean cornTrigger = TimeJobUtils.getTriggerBean(job);
          cornTrigger.setJobDetail(jobDetail);
          if (!StringUtils.isBlank(job.getJavaTimeZone())) {
            cornTrigger.setTimeZone(TimeZone.getTimeZone(job.getJavaTimeZone()));
          }
          // 加入调度器
          scheduler.addJob(jobDetail, true);
          scheduler.scheduleJob(cornTrigger.getObject());
          
        }
      }
    } catch (Exception e) {
      LOGGER.error("{}", e);
    }
  }

  @Override
  public void contextDestroyed(ServletContextEvent event) {
    // Do nothing
  }

}
